<!-- 商城界面 -->
<script setup>
import { ref, onMounted, computed } from 'vue'
import Card from '@/components/card.vue'

const files = ref([])
const loading = ref(true)
const error = ref('')

// 筛选和搜索相关状态
const selectedTag = ref('') // 当前选中的标签
const searchQuery = ref('') // 搜索关键词

// 服务器地址
const SERVER_URL = 'http://192.168.1.119:5000'

// 获取文件列表
const fetchFiles = async () => {
  try {
    loading.value = true
    error.value = ''
    
    const response = await fetch(`${SERVER_URL}/files`)
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }
    
    const data = await response.json()
    files.value = data.files || []
  } catch (err) {
    console.error('获取文件列表失败:', err)
    error.value = '获取文件列表失败，请检查服务器连接'
  } finally {
    loading.value = false
  }
}

// 下载文件
const downloadFile = (fileId, fileName) => {
  const downloadUrl = `${SERVER_URL}/download/${fileId}`
  // 创建一个临时的a标签来触发下载
  const link = document.createElement('a')
  link.href = downloadUrl
  // 移除download属性，让服务器的Content-Disposition头决定文件名
  link.target = '_blank'
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}

// 删除文件
const deleteFile = async (fileData) => {
  try {
    const response = await fetch(`${SERVER_URL}/delete/${fileData.id}`, {
      method: 'DELETE'
    })
    
    if (response.ok) {
      // 删除成功，从本地列表中移除该文件
      files.value = files.value.filter(file => file.id !== fileData.id)
      console.log('文件删除成功:', fileData.display_name || fileData.original_name)
    } else {
      console.error('删除文件失败:', response.statusText)
      alert('删除文件失败，请稍后重试')
    }
  } catch (err) {
    console.error('删除文件时发生错误:', err)
    alert('删除文件时发生错误，请检查网络连接')
  }
}

// 格式化文件大小
const formatFileSize = (bytes) => {
  if (bytes === 0) return '0 Bytes'
  const k = 1024
  const sizes = ['Bytes', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

// 从所有文件中提取唯一标签
const allTags = computed(() => {
  const tagSet = new Set()
  files.value.forEach(file => {
    if (file.tags && Array.isArray(file.tags)) {
      file.tags.forEach(tag => tagSet.add(tag))
    }
  })
  return Array.from(tagSet).sort()
})

// 筛选后的文件列表
const filteredFiles = computed(() => {
  let result = files.value

  // 按标签筛选
  if (selectedTag.value) {
    result = result.filter(file => 
      file.tags && file.tags.includes(selectedTag.value)
    )
  }

  // 按搜索关键词筛选
  if (searchQuery.value.trim()) {
    const query = searchQuery.value.trim().toLowerCase()
    result = result.filter(file => {
      const fileName = (file.display_name || file.original_name || '').toLowerCase()
      const description = (file.description || '').toLowerCase()
      return fileName.includes(query) || description.includes(query)
    })
  }

  return result
})

// 选择标签
const selectTag = (tag) => {
  selectedTag.value = selectedTag.value === tag ? '' : tag
}

// 清除所有筛选
const clearFilters = () => {
  selectedTag.value = ''
  searchQuery.value = ''
}

// 组件挂载时获取文件列表
onMounted(() => {
  fetchFiles()
})
</script>
<template>
    <div class="container">
        <!-- 顶部区域 -->
        <div class="top_area">
            <!-- 标签筛选区域 -->
            <div class="tags-section">
                <div class="tags-header">
                    <span class="tags-title">标签筛选:</span>
                    <button 
                        v-if="selectedTag || searchQuery" 
                        @click="clearFilters" 
                        class="clear-btn"
                    >
                        清除筛选
                    </button>
                </div>
                <div class="tags-container">
                    <button
                        v-for="tag in allTags"
                        :key="tag"
                        @click="selectTag(tag)"
                        :class="['tag-btn', { active: selectedTag === tag }]"
                    >
                        {{ tag }}
                    </button>
                    <div v-if="allTags.length === 0" class="no-tags">暂无标签</div>
                </div>
            </div>
            
            <!-- 搜索区域 -->
            <div class="search-section">
                <div class="search-container">
                    <input
                        v-model="searchQuery"
                        type="text"
                        placeholder="搜索文件名称或描述..."
                        class="search-input"
                    />
                    <div class="search-icon">🔍</div>
                </div>
            </div>
        </div>

        <!-- 加载状态 -->
        <div v-if="loading" class="loading">
            <div class="loading-spinner"></div>
            <p>加载中...</p>
        </div>
        
        <!-- 错误状态 -->
        <div v-else-if="error" class="error">
            <p>{{ error }}</p>
            <button @click="fetchFiles" class="retry-btn">重试</button>
        </div>

        <!-- 正常状态下的内容 -->
        <template v-else>
            <!-- 结果统计 -->
            <div class="results-info">
                <span class="results-count">
                    找到 {{ filteredFiles.length }} 个文件
                    <span v-if="selectedTag || searchQuery" class="filter-info">
                        (已筛选)
                    </span>
                </span>
            </div>

            <!-- 文件列表 -->
            <div class="files-grid">
            <div v-if="filteredFiles.length === 0 && files.length > 0" class="empty">
                <p>没有找到符合条件的文件</p>
                <button @click="clearFilters" class="clear-filters-btn">清除筛选条件</button>
            </div>
            <div v-else-if="files.length === 0" class="empty">
                <p>暂无文件</p>
            </div>
            <Card 
                v-else
                v-for="file in filteredFiles" 
                :key="file.id"
                :title="file.display_name || file.original_name"
                :file-data="file"
                :preview-url="file.preview_url ? `${SERVER_URL}/preview/${file.preview_url}` : null"
                :file-size="formatFileSize(file.size)"
                :file-type="file.type"
                :tags="file.tags"
                :description="file.description"
                @download="downloadFile(file.id, file.display_name || file.original_name)"
                @delete="deleteFile"
            />
            </div>
        </template>
    </div>
</template>
<style scoped>
.container {
    position: absolute;
    /* 计算剩余空间：总宽度 - 侧边栏宽度(80px) - 侧边栏左边距(1vw) - 间距(1vw) */
    left: calc(80px + 2vw);
    top: 0vh;
    width: calc(100vw - 80px - 3vw);
    height: 96vh;
    border-radius: 12px;
    /*background-color: #f5f5f5;*/
    display: flex;
    justify-content: flex-start;
    align-items: flex-start;
    box-sizing: border-box;
    padding: 20px;
    overflow: hidden; /* 隐藏横向和纵向滚动条 */
    overflow-x: hidden; /* 强制隐藏横向滚动条 */
    overflow-y: auto; /* 允许纵向滚动以容纳内容 */
    /* 隐藏滚动条样式 */
    scrollbar-width: none; /* Firefox */
    -ms-overflow-style: none; /* IE和Edge */
    flex-direction: column;
}

/* 隐藏滚动条 */
.container::-webkit-scrollbar {
    display: none; /* Chrome, Safari, Opera */
    width: 0;
    height: 0;
}

/* 文件网格布局 */
.files-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(335px, 1fr));
    gap: 20px;
    width: 100%;
    margin-top: 20px;
}

/* 加载状态 */
.loading {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 200px;
    color: #666;
}

.loading-spinner {
    width: 40px;
    height: 40px;
    border: 4px solid #f3f3f3;
    border-top: 4px solid #007bff;
    border-radius: 50%;
    animation: spin 1s linear infinite;
    margin-bottom: 16px;
}

@keyframes spin {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
}

/* 错误状态 */
.error {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 200px;
    color: #dc3545;
    text-align: center;
}

.retry-btn {
    background: #007bff;
    color: white;
    border: none;
    padding: 8px 16px;
    border-radius: 4px;
    cursor: pointer;
    margin-top: 10px;
    transition: background-color 0.3s;
}

.retry-btn:hover {
    background: #0056b3;
}

/* 空状态 */
.empty {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 200px;
    color: #666;
    font-size: 18px;
    grid-column: 1 / -1;
}

/* 顶部区域样式 */
.top_area {
    width: calc(100% - 80px);
    min-height: 120px;
    border-radius: 12px;
    background: rgba(255, 255, 255, 0.9);
    backdrop-filter: blur(10px);
    border: 1px solid rgba(255, 255, 255, 0.2);
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
    display: flex;
    flex-direction: column;
    padding: 20px;
    margin-bottom: 20px;
    gap: 15px;
}

/* 标签筛选区域 */
.tags-section {
    flex: 1;
}

.tags-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 10px;
}

.tags-title {
    font-weight: 600;
    color: #333;
    font-size: 14px;
}

.clear-btn {
    background: linear-gradient(135deg, #ff6b6b, #ee5a52);
    color: white;
    border: none;
    padding: 6px 12px;
    border-radius: 20px;
    font-size: 12px;
    cursor: pointer;
    transition: all 0.3s ease;
    box-shadow: 0 2px 8px rgba(255, 107, 107, 0.3);
}

.clear-btn:hover {
    transform: translateY(-1px);
    box-shadow: 0 4px 12px rgba(255, 107, 107, 0.4);
}

.tags-container {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
    max-height: 60px;
    overflow-y: auto;
    scrollbar-width: none;
    -ms-overflow-style: none;
}

.tags-container::-webkit-scrollbar {
    display: none;
}

.tag-btn {
    background: linear-gradient(135deg, #667eea, #764ba2);
    color: white;
    border: none;
    padding: 6px 14px;
    border-radius: 20px;
    font-size: 12px;
    cursor: pointer;
    transition: all 0.3s ease;
    box-shadow: 0 2px 8px rgba(102, 126, 234, 0.3);
    white-space: nowrap;
}

.tag-btn:hover {
    transform: translateY(-1px);
    box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
}

.tag-btn.active {
    background: linear-gradient(135deg, #4facfe, #00f2fe);
    box-shadow: 0 4px 12px rgba(79, 172, 254, 0.5);
    transform: translateY(-1px);
}

.no-tags {
    color: #999;
    font-style: italic;
    font-size: 14px;
}

/* 搜索区域 */
.search-section {
    flex-shrink: 0;
}

.search-container {
    position: relative;
    max-width: 400px;
}

.search-input {
    width: 100%;
    padding: 12px 45px 12px 16px;
    border: 2px solid rgba(102, 126, 234, 0.2);
    border-radius: 25px;
    font-size: 14px;
    background: rgba(255, 255, 255, 0.8);
    backdrop-filter: blur(10px);
    transition: all 0.3s ease;
    outline: none;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.search-input:focus {
    border-color: #667eea;
    box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
    transform: translateY(-1px);
}

.search-input::placeholder {
    color: #999;
}

.search-icon {
    position: absolute;
    right: -45px;
    top: 50%;
    transform: translateY(-50%);
    font-size: 16px;
    color: #667eea;
    pointer-events: none;
}

/* 结果统计 */
.results-info {
    margin: 10px 0;
    padding: 10px 0;
}

.results-count {
    color: #666;
    font-size: 14px;
    font-weight: 500;
}

.filter-info {
    color: #667eea;
    font-weight: 600;
}

/* 清除筛选按钮 */
.clear-filters-btn {
    background: linear-gradient(135deg, #667eea, #764ba2);
    color: white;
    border: none;
    padding: 10px 20px;
    border-radius: 25px;
    font-size: 14px;
    cursor: pointer;
    margin-top: 10px;
    transition: all 0.3s ease;
    box-shadow: 0 2px 8px rgba(102, 126, 234, 0.3);
}

.clear-filters-btn:hover {
    transform: translateY(-1px);
    box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
}
</style>